#include <iostream>
#include <signal.h>
#include "../comm/httplib.h"
#include "oj_control.hpp"

using namespace httplib;
using namespace ns_control;

static Control *ctrl_ptr=nullptr;
void recovery(int)
{
    ctrl_ptr->Recovery();
}

int main()
{
    signal(SIGQUIT,recovery);
    //⽤⼾请求的服务路由功能
    Server svr;
    Control ctrl;

    ctrl_ptr=&ctrl;
    //获取所有问题列表
    svr.Get("/all_questions",[&ctrl](const Request& req,Response& resp){
        string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html,"text/html; charset=utf-8");
    });

    //获取单个题目
    // /question/100 -> 正则匹配
    // R"()", 原始字符串raw string,保持字符串内容的原貌，不⽤做相关的转义
    svr.Get(R"(/question/(\d+))",[&ctrl](const Request& req,Response& resp){
        std::string match=req.matches[1];
        string html;
        ctrl.OneQuestion(match,&html);
        resp.set_content(html,"text/html; charset=utf-8");
    });

    //编译运行单个题目
    svr.Post(R"(/judge/(\d+))",[&ctrl](const Request& req,Response& resp){
        std::string match=req.matches[1];
        std::string in_json=req.body;
        std::string out_json;
        ctrl.Judge(match,in_json,&out_json);
        resp.set_content(out_json,"application/json; charset=utf-8");
    });

    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0", 8080);

    return 0;
}